//
//  MomentsView.swift
//  WeChatClient
//
//  Created by AI Assistant on 2025/10/31.
//

import SwiftUI

struct MomentsView: View {
    @EnvironmentObject var discoverViewModel: DiscoverViewModel
    
    var body: some View {
        ZStack {
            if discoverViewModel.isLoading {
                ProgressView("加载中...")
            } else {
                ScrollView {
                    LazyVStack(spacing: 0) {
                        // 个人信息头部
                        MomentsHeaderView()
                            .environmentObject(discoverViewModel)
                        
                        Divider()
                            .padding(.vertical, 10)
                        
                        // 朋友圈内容
                        ForEach(discoverViewModel.moments) { moment in
                            MomentCellView(moment: moment)
                                .environmentObject(discoverViewModel)
                            
                            Divider()
                                .padding(.vertical, 10)
                        }
                    }
                }
                .refreshable {
                    discoverViewModel.refreshMoments()
                }
            }
        }
        .navigationTitle("朋友圈")
        .navigationBarTitleDisplayMode(.inline)
        .toolbar {
            ToolbarItem(placement: .navigationBarTrailing) {
                Button(action: {
                    discoverViewModel.showNewMomentSheet = true
                }) {
                    Image(systemName: "plus")
                }
            }
        }
        .sheet(isPresented: $discoverViewModel.showNewMomentSheet) {
            NewMomentView()
                .environmentObject(discoverViewModel)
        }
    }
}

struct MomentsHeaderView: View {
    @EnvironmentObject var discoverViewModel: DiscoverViewModel
    
    var body: some View {
        VStack(spacing: 0) {
            // 背景图
            Rectangle()
                .fill(LinearGradient(
                    gradient: Gradient(colors: [.blue.opacity(0.6), .green.opacity(0.4)]),
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                ))
                .frame(height: 200)
                .overlay(
                    HStack {
                        Spacer()
                        VStack(spacing: 8) {
                            Image(systemName: User.currentUser.avatar)
                                .font(.system(size: 60))
                                .foregroundColor(.white)
                                .frame(width: 80, height: 80)
                                .background(Color.white.opacity(0.2))
                                .clipShape(RoundedRectangle(cornerRadius: 12))
                            
                            Text(User.currentUser.displayName)
                                .font(.system(size: 16, weight: .medium))
                                .foregroundColor(.white)
                        }
                        .padding(.trailing, 20)
                        .padding(.bottom, 20)
                        .padding(.top, 60)
                    },
                    alignment: .bottomTrailing
                )
        }
        .background(Color.white)
    }
}

struct MomentCellView: View {
    let moment: Moment
    @EnvironmentObject var discoverViewModel: DiscoverViewModel
    @State private var showCommentInput = false
    @State private var commentText = ""
    
    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            // 用户信息
            HStack(spacing: 12) {
                Image(systemName: moment.user.avatar)
                    .font(.system(size: 40))
                    .foregroundColor(.blue)
                    .frame(width: 45, height: 45)
                    .background(Color.gray.opacity(0.2))
                    .clipShape(RoundedRectangle(cornerRadius: 8))
                
                VStack(alignment: .leading, spacing: 2) {
                    Text(moment.user.displayName)
                        .font(.system(size: 15, weight: .medium))
                        .foregroundColor(.blue)
                    
                    Text(discoverViewModel.formatTimeAgo(moment.timestamp))
                        .font(.system(size: 12))
                        .foregroundColor(.secondary)
                }
                
                Spacer()
            }
            
            // 内容
            if !moment.content.isEmpty {
                Text(moment.content)
                    .font(.system(size: 15))
                    .foregroundColor(.primary)
                    .padding(.leading, 57)
            }
            
            // 媒体内容
            if !moment.images.isEmpty || moment.contentType == .video {
                MomentMediaView(moment: moment)
                    .padding(.leading, 57)
            }
            
            // 互动区域
            HStack {
                Spacer()
                
                HStack(spacing: 15) {
                    Button(action: {
                        discoverViewModel.toggleLike(for: moment)
                    }) {
                        Image(systemName: moment.isLikedByCurrentUser ? "heart.fill" : "heart")
                            .font(.system(size: 16))
                            .foregroundColor(moment.isLikedByCurrentUser ? .red : .secondary)
                    }
                    
                    Button(action: {
                        showCommentInput.toggle()
                    }) {
                        Image(systemName: "bubble.left")
                            .font(.system(size: 16))
                            .foregroundColor(.secondary)
                    }
                }
                .padding(.horizontal, 12)
                .padding(.vertical, 6)
                .background(Color.gray.opacity(0.1))
                .clipShape(RoundedRectangle(cornerRadius: 16))
            }
            .padding(.leading, 57)
            
            // 点赞和评论
            if !moment.likes.isEmpty || !moment.comments.isEmpty {
                VStack(alignment: .leading, spacing: 4) {
                    // 点赞列表
                    if !moment.likes.isEmpty {
                        HStack(spacing: 4) {
                            Image(systemName: "heart.fill")
                                .font(.system(size: 12))
                                .foregroundColor(.red)
                            
                            Text(moment.likes.map { $0.displayName }.joined(separator: ", "))
                                .font(.system(size: 13))
                                .foregroundColor(.blue)
                                .lineLimit(2)
                        }
                    }
                    
                    // 评论列表
                    ForEach(moment.comments) { comment in
                        HStack(alignment: .top, spacing: 4) {
                            Text(comment.user.displayName)
                                .font(.system(size: 13, weight: .medium))
                                .foregroundColor(.blue)
                            
                            Text(": \(comment.content)")
                                .font(.system(size: 13))
                                .foregroundColor(.primary)
                        }
                    }
                }
                .padding(.horizontal, 12)
                .padding(.vertical, 8)
                .background(Color.gray.opacity(0.05))
                .clipShape(RoundedRectangle(cornerRadius: 8))
                .padding(.leading, 57)
            }
            
            // 评论输入框
            if showCommentInput {
                HStack {
                    TextField("写评论...", text: $commentText)
                        .textFieldStyle(RoundedBorderTextFieldStyle())
                    
                    Button("发送") {
                        if !commentText.isEmpty {
                            discoverViewModel.addComment(to: moment, content: commentText)
                            commentText = ""
                            showCommentInput = false
                        }
                    }
                    .disabled(commentText.isEmpty)
                }
                .padding(.leading, 57)
            }
        }
        .padding(.horizontal, 16)
    }
}

struct MomentMediaView: View {
    let moment: Moment
    
    var body: some View {
        switch moment.contentType {
        case .singleImage:
            SingleImageView(imageName: moment.images.first ?? "photo")
            
        case .multipleImages:
            MultipleImagesGridView(images: moment.images)
            
        case .video:
            VideoThumbnailView()
            
        case .text:
            EmptyView()
        }
    }
}

struct SingleImageView: View {
    let imageName: String
    
    var body: some View {
        ZStack {
            LinearGradient(
                gradient: Gradient(colors: [
                    Color.blue.opacity(0.3),
                    Color.green.opacity(0.3),
                    Color.orange.opacity(0.3)
                ]),
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
            .frame(width: 140, height: 120)
            .clipShape(RoundedRectangle(cornerRadius: 8))
            
            Image(systemName: imageName)
                .font(.system(size: 60))
                .foregroundColor(.white.opacity(0.8))
        }
    }
}

struct MultipleImagesGridView: View {
    let images: [String]
    
    var body: some View {
        let gridColumns = min(images.count, 3)
        let columns = Array(repeating: GridItem(.flexible(), spacing: 4), count: gridColumns)
        
        LazyVGrid(columns: columns, spacing: 4) {
            ForEach(Array(images.prefix(9).enumerated()), id: \.offset) { index, imageName in
                ImageGridItem(imageName: imageName, index: index)
            }
        }
    }
}

struct ImageGridItem: View {
    let imageName: String
    let index: Int
    
    var body: some View {
        ZStack {
            getGradientForIndex()
                .frame(width: 80, height: 80)
                .clipShape(RoundedRectangle(cornerRadius: 6))
            
            Image(systemName: imageName)
                .font(.system(size: 25))
                .foregroundColor(.white.opacity(0.9))
        }
    }
    
    private func getGradientForIndex() -> LinearGradient {
        let gradientIndex = index % 5
        
        switch gradientIndex {
        case 0:
            return LinearGradient(
                gradient: Gradient(colors: [Color.red.opacity(0.4), Color.pink.opacity(0.4)]),
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
        case 1:
            return LinearGradient(
                gradient: Gradient(colors: [Color.blue.opacity(0.4), Color.cyan.opacity(0.4)]),
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
        case 2:
            return LinearGradient(
                gradient: Gradient(colors: [Color.green.opacity(0.4), Color.mint.opacity(0.4)]),
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
        case 3:
            return LinearGradient(
                gradient: Gradient(colors: [Color.orange.opacity(0.4), Color.yellow.opacity(0.4)]),
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
        default:
            return LinearGradient(
                gradient: Gradient(colors: [Color.purple.opacity(0.4), Color.indigo.opacity(0.4)]),
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
        }
    }
}

struct VideoThumbnailView: View {
    var body: some View {
        ZStack {
            LinearGradient(
                gradient: Gradient(colors: [
                    Color.black.opacity(0.7),
                    Color.gray.opacity(0.5)
                ]),
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
            .frame(width: 160, height: 120)
            .clipShape(RoundedRectangle(cornerRadius: 8))
            
            VStack(spacing: 8) {
                Image(systemName: "play.circle.fill")
                    .font(.system(size: 40))
                    .foregroundColor(.white)
                
                Text("视频")
                    .font(.system(size: 12))
                    .foregroundColor(.white.opacity(0.8))
            }
        }
    }
}
